from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
import json
import os

class weather:
    def __init__(self,d,c,D,P,h,l,_c,_D,_P):
        self.date=d
        self.climate1=c
        self.windDirection1=D
        self.windPower1=P
        self.high=h
        self.low=l
        self.climate2=_c
        self.windDirection2=_D
        self.windPower2=_P

class weatherList:
    def __init__(self):
        self.weatherlist=[]

def getWeather(desti :str): 
    options = Options()
    options.add_argument('--no-sandbox')
    options.add_argument('--headless')#设置无头模式
    options.add_argument('--disable-gpu')
    options.add_argument("--blink-settings=imagesEnabled=false")#禁止图片加载
    options.add_argument("--disable-application-cache")
    driver = webdriver.Chrome(options=options)
    driver.execute_cdp_cmd('Network.setCacheDisabled', {'cacheDisabled': True})#禁用缓存
    driver.maximize_window()#防止无法找到页面元素
    driver.get('https://weather.cma.cn/')
    input=driver.find_element(By.ID,'searchInput')
    input.send_keys(desti)
    ActionChains(driver).pause(0.1).send_keys('\ue007').perform()#搜索对应城市并获取目标页面
    driver.implicitly_wait(2)

    List=weatherList()
    today=driver.find_element(By.XPATH,'//*[@id="dayList"]/div[1]')
    items = today.find_elements(By.CLASS_NAME,'day-item')
    high = today.find_element(By.XPATH,'//*[@id="dayList"]/div[1]/div[6]/div/div[1]')
    low = today.find_element(By.XPATH,'//*[@id="dayList"]/div[1]/div[6]/div/div[2]')
    Today=weather(items[0].text,items[2].text,items[3].text,items[4].text,high.text,low.text,items[7].text,items[8].text,items[9].text)
    List.weatherlist.append(Today)

    tomorrow=driver.find_element(By.XPATH,'//*[@id="dayList"]/div[2]')
    items = tomorrow.find_elements(By.CLASS_NAME,'day-item')
    high = tomorrow.find_element(By.XPATH,'//*[@id="dayList"]/div[2]/div[6]/div/div[1]')
    low = tomorrow.find_element(By.XPATH,'//*[@id="dayList"]/div[2]/div[6]/div/div[2]')
    Tomorrow=weather(items[0].text,items[2].text,items[3].text,items[4].text,high.text,low.text,items[7].text,items[8].text,items[9].text)
    List.weatherlist.append(Tomorrow)
    
    next=driver.find_element(By.XPATH,'//*[@id="dayList"]/div[3]')
    items = next.find_elements(By.CLASS_NAME,'day-item')
    high = next.find_element(By.XPATH,'//*[@id="dayList"]/div[3]/div[6]/div/div[1]')
    low = next.find_element(By.XPATH,'//*[@id="dayList"]/div[3]/div[6]/div/div[2]')
    Next=weather(items[0].text,items[2].text,items[3].text,items[4].text,high.text,low.text,items[7].text,items[8].text,items[9].text)
    List.weatherlist.append(Next)

    driver.quit()

    with open('temp/temp.json','w+') as f:
        json.dump(List,f,default=lambda obj:obj.__dict__,ensure_ascii=False)#将天气数据缓存为json
